package ink.lovejinhu.leetcode;

import org.junit.Test;

/**
 * @author jinhu
 * created 2021-04-27 20:02
 */
public class Solution_0014 {
    /**
     * 思路:
     * <p>
     * <p>
     * 1 2 3 4
     * a a  a a
     * b d  c f
     *
     * @param strs
     * @return
     */
    public String longestCommonPrefix(String[] strs) {
        int min = Integer.MAX_VALUE;
        int record = Integer.MIN_VALUE; //记录j的值
        char row;
        for (int i = 0; i < strs.length; i++) {   //找最小长度的字符串
            if (strs[i] == null || strs[i].length() == 0) {   //若有一个是空串
                return "";

            }
            if (min > strs[i].length()) {
                min = strs[i].length();
            }
        }
        char[][] temp = new char[strs.length][min];
        for (int i = 0; i < strs.length; i++) {
            char[] chars = strs[i].toCharArray();
            for (int j = 0; j < min; j++) {
                temp[i][j] = chars[j];
                System.out.print(temp[i][j] + "  ");
            }
            System.out.println("");
        }
        cert:
        for (int j = 0; j < min; j++) {
            row = temp[0][j];
            for (int i = 1; i < strs.length; i++) {
                if (temp[i][j] != row) {
                    record = j;
                    break cert;
                }
            }

        }

        if (record < 0) {   //一个都匹配不上
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int j = 0; j <= record; j++) {
            stringBuilder.append(temp[0][j]);
        }


        return stringBuilder.toString();
    }

    @Test
    public void test() {
        //  String[] strings = {"abc", "ab", "a"};
        String[] strings = {"flower", "flow", "flight"};
        String s = this.longestCommonPrefix(strings);
        System.out.println(s);

    }
}
